import torch.nn.functional as F
import torch.nn as nn
import torch


class DnSRFD(nn.Module):
    def __init__(self, n_channels=1, n_classes=1,growth_rate=96, bilinear=True):
        super(DnSRFD, self).__init__()
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.bilinear = bilinear

        self.SFE = DoubleConv(n_channels, 64)
        self.down1 = Down(64, 128, growth_rate)
        self.down2 = Down(128, 256, growth_rate)
        self.down3 = Down(256, 512, growth_rate)
        factor = 2 if bilinear else 1
        self.down4 = Down(512, 1024 // factor, growth_rate)
        self.up1 = Up(1024, 512 // factor, bilinear)
        self.up2 = Up(512, 256 // factor, bilinear)
        self.up3 = Up(256, 128 // factor, bilinear)
        self.up4 = Up(128, 64, bilinear)
        self.outc = OutConv(64, n_classes)

    def forward(self, x):
        y = x
        x1 = self.SFE(x)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)

        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        logits = self.outc(x)
        return logits


class DoubleConv(nn.Module):
    """(convolution => [BN] => ReLU) * 2"""

    def __init__(self, in_channels, out_channels, mid_channels=None):
        super().__init__()
        if not mid_channels:
            mid_channels = out_channels
        self.double_conv = nn.Sequential(
            nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),
            nn.BatchNorm2d(mid_channels),
            nn.ELU(inplace=True),
            nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),
            nn.BatchNorm2d(out_channels),
            nn.ELU(inplace=True),
        )

    def forward(self, x):
        return self.double_conv(x)


class Down(nn.Module):
    """Downscaling with maxpool then double conv"""

    def __init__(self, in_channels, out_channels, growth_rate):
        super().__init__()
        self.dense_block = DenseBlock(num_layers=6,in_channels=in_channels,growth_rate=growth_rate)
        self.maxpool_conv = nn.Sequential(
            nn.MaxPool2d(2),
            DoubleConv(in_channels, out_channels)
        )

    def forward(self, x):
        return self.maxpool_conv(self.dense_block(x))


class Up(nn.Module):
    """Upscaling then double conv"""

    def __init__(self, in_channels, out_channels, bilinear=True):
        super().__init__()

        # if bilinear, use the normal convolutions to reduce the number of channels
        if bilinear:
            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
            self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)
        else:
            self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
            self.conv = DoubleConv(in_channels, out_channels)

    def forward(self, x1, x2):
        x1 = self.up(x1)
        # input is CHW
        diffY = x2.size()[2] - x1.size()[2]
        diffX = x2.size()[3] - x1.size()[3]

        # print(x1.shape)
        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2, diffY // 2, diffY - diffY // 2])
        # print(x1.shape)
        # if you have padding issues, see
        # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a
        # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd
        x = torch.cat([x2, x1], dim=1)
        return self.conv(x)


class OutConv(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(OutConv, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)

    def forward(self, x):
        return self.conv(x)

# 定义密集块子块-- Bottle-Neck
def conv_bottleneck(in_channels, out_channels):
    p_c1 = int(out_channels // 4)
    p_c2 = int(out_channels // 2)
    p_c3 = int(out_channels // 4)

    block = torch.nn.Sequential(
        Inception(in_c=in_channels,c1=p_c1,c2=[int(p_c2//2),p_c2],c3=[int(p_c3//2),p_c3]),
        # torch.nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1, bias=False),
        # torch.nn.BatchNorm2d(out_channels),
        # torch.nn.ELU(inplace=True),
    )
    return block

# 定义密集块-- Dense-Block
class DenseBlock(torch.nn.Module):

    def __init__(self, num_layers, in_channels, growth_rate):
        '''
        初始化密集块网络

        :param num_layers: 密集块中bottleneck的层数
        :param in_channels: 当前密集块的输入通道数
        :param growth_rate: 密集块的增长率
        '''
        super(DenseBlock, self).__init__()
        block = []
        channel = in_channels
        # 自定义生成密集块并封装到block中
        for i in range(num_layers):
            block.append(conv_bottleneck(channel, growth_rate))
            channel += growth_rate

        self.covn = torch.nn.Sequential(
            torch.nn.Conv2d(in_channels=channel, out_channels=in_channels, kernel_size=1, stride=1),
        )

        # 将密集块序列化成为网络的一部分
        self.DenseBlock_Net = torch.nn.ModuleList(block)

    def forward(self, x):
        Y = x
        for layer in self.DenseBlock_Net:
            out = layer(x)
            # 将两个张量拼接在一起（按维数1拼接）
            x = torch.cat((x, out), dim=1)

        return Y + self.covn(x)

class Inception(nn.Module):
    def __init__(self,in_c,c1,c2,c3):
        super(Inception,self).__init__()
        self.p1 = nn.Sequential(
            nn.Conv2d(in_c,c1,kernel_size=1),
            nn.BatchNorm2d(c1),
            nn.ELU(inplace=True)
        )
        self.p2 = nn.Sequential(
            nn.Conv2d(in_c,c2[0],kernel_size=1),
            nn.BatchNorm2d(c2[0]),
            nn.ELU(inplace=True),
            nn.Conv2d(c2[0], c2[1], kernel_size=3,padding=1),
            nn.BatchNorm2d(c2[1]),
            nn.ELU(inplace=True)
        )
        self.p3 = nn.Sequential(
            nn.Conv2d(in_c, c3[0], kernel_size=1),
            nn.BatchNorm2d(c3[0]),
            nn.ELU(inplace=True),
            nn.Conv2d(c3[0], c3[1], kernel_size=3, stride=1,padding=1),
            nn.BatchNorm2d(c3[1]),
            nn.ELU(inplace=True),
            nn.Conv2d(c3[1], c3[1], kernel_size=3, stride=1,padding=1),
            nn.BatchNorm2d(c3[1]),
            nn.ELU(inplace=True)
        )
    def forward(self, x):
        p1 = self.p1(x)
        p2 = self.p2(x)
        p3 = self.p3(x)
        # p4 = self.p4(x)
        return torch.cat((p1,p2,p3),dim=1)